package car.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import dhu.com.car.common.R;
import dhu.com.car.entity.Car;
import dhu.com.car.entity.Orders;
import dhu.com.car.service.CarService;
import dhu.com.car.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


@RestController
@RequestMapping("/car")
public class CarController {

    @Autowired
    private CarService carService;

    @Autowired
    private OrdersService ordersService;

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String brand,String quality,String colour,String seat){
        Page<Car> dishPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Car> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(brand!=null,Car::getBrand,brand);
        if(quality!=null&&!quality.equals("")){
            queryWrapper.eq(Car::getQuality,quality);
        }
        if(colour!=null&&!colour.equals("")){
            queryWrapper.eq(Car::getColour,colour);
        }
        if(seat!=null&&!seat.equals("")){
            queryWrapper.eq(Car::getSeat,seat);
        }
        queryWrapper.orderByAsc(Car::getPrice);

        carService.page(dishPage,queryWrapper);


        return R.success(dishPage);
    }

    @PostMapping
    public R<String> save(@RequestBody Car car){
        carService.save(car);
        return R.success("新增房屋成功");
    }

    /**
     *修改房子信息
     * @param
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Car car){
        carService.updateById(car);

        return R.success("修改房屋成功");
    }

    /**
     * 根据id查询房子信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Car> get(@PathVariable Long id){

        Car car = carService.getById(id);

        return R.success(car);
    }

    @DeleteMapping
    public R<String> delete(Long[] ids){

        for(Long id:ids){
            carService.removeById(id);
        }
        return R.success("状态更新成功");
    }

    @PostMapping("/buy")
    public R<String> buyHouse(HttpServletRequest request, @RequestBody Car carInfo){
        Car car = carService.getById(carInfo.getId());
        if(car!=null){
            Orders orders = new Orders();
            orders.setCId(car.getId());
            orders.setPrice(car.getPrice());
            orders.setTime(LocalDateTime.now());
            orders.setPrice(car.getPrice());
            Integer userId = (Integer) request.getSession().getAttribute("employee");
            orders.setUId(userId);
            ordersService.save(orders);
            carService.removeById(car.getId());
            return R.success("购买成功");
        }else {
            return R.error("房屋售罄");
        }
    }


}
